package com.alm.framework.framework.interceptor.auth;

import com.alm.common.auth.CipherInfo;
import com.alm.common.core.domain.AjaxResult;
import com.alm.common.utils.AuthUtil;
import com.alm.common.utils.TimeUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author ywy
 * @date 2024/8/9
 * 校验过期时间拦截器
 */
@Component
public class TimeExpirationInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        // 读取授权文件，不存在直接拦截
        CipherInfo cipherInfo = AuthUtil.getPlaintextObj();
        if(cipherInfo != null) {
            // 绕过
            if(cipherInfo.getExpiredTime().equalsIgnoreCase("alm")) {
                return true;
            }
            long timeMillis = System.currentTimeMillis();
//            cipherInfo.setExpiredTime("2024-08-01");
            // 判断过期时间
            if(StringUtils.isNotBlank(cipherInfo.getExpiredTime()) && timeMillis < TimeUtil.strToDateNoHour(cipherInfo.getExpiredTime()).getTime()) {
                System.out.println("未过期正常使用，当前时间:" + TimeUtil.format(timeMillis) +"  过期时间："  + cipherInfo.getExpiredTime());
                return true;
            }
        }

        AuthUtil.sendJsonMessage(response, AjaxResult.buildCodeAndMsg(700001, "系统使用权限已过期，请联系管理员！ 过期时间：" +
                (StringUtils.isNotBlank(cipherInfo.getExpiredTime()) ? cipherInfo.getExpiredTime() : "")));
        return false;
    }
}
